package org.cx.comparator;

import org.cx.comparator.annotations.ComparatorParam;
import org.cx.comparator.compare.mode.ObjectCompareContext;
import org.cx.comparator.map.ComparatorMap;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Getter
public class ComparatorMethod {

    private final Class equatorInterface;
    private final Method method;
    private final ComparatorConfiguration configuration;
    private ComparatorMap comparatorMap;
    private Map<Integer, String> params = new HashMap<>();

    public ComparatorMethod(Class equatorInterface, Method method, ComparatorConfiguration configuration) {
        this.equatorInterface = equatorInterface;
        this.method = method;
        this.configuration = configuration;
        final int parameterCount = method.getParameterCount();
        if (parameterCount < 2) {
            throw new ComparatorException("方法定义不合法，至少要有两个参数！");
        }

        for (int i = 0; i < method.getParameterAnnotations().length; i++) {
            final int index = i;
            final Annotation[] parameterAnnotation = method.getParameterAnnotations()[i];
            Arrays.stream(parameterAnnotation)
                    .filter(anno -> anno.annotationType() == ComparatorParam.class)
                    .findFirst()
                    .map(anno -> params.put(index, ((ComparatorParam) anno).value()));
        }
    }


    public Object execute(Object[] args) {

        if (comparatorMap == null) {
            comparatorMap = configuration.getMapProcessor().build(this.method);
            if (comparatorMap == null) {
                throw new ComparatorException("未找到比较配置！");
            }
        }

        Object source = args[0];
        Object target = args[1];
        return configuration.getObjectCompare().compare(new ObjectCompareContext(source, target, this, args));
    }


}
